<?php

namespace nimo\domains\car_balance\controllers;

use App;
use BaseController;
use nimo\domains\car_balance\Model\CarAuctionType;
use nimo\domains\car_balance\Model\CarMaker;
use nimo\domains\car_balance\Model\CustomerBillType;
use nimo\domains\car_balance\Model\Penalty;
use nimo\domains\car_balance\Model\ReAuction;
use Redirect;
use Response;
use Input;
use Request;
use Sentry;
use Session;
use Validator;
use View;
use Config;
use nimo\domains\master\models\Domain;
use nimo\domains\car_balance\Model\PurchaseCar;
use nimo\domains\car_balance\Model\Customer;
use nimo\domains\car_balance\Model\VanningCompanyBranch;
use nimo\domains\car_balance\Model\CarAuction;
use nimo\domains\car_balance\Model\ServiceCompany;
use nimo\domains\car_balance\Model\TransportFeePay;
use nimo\domains\car_balance\Model\TransportFeeClaim;

class CarController extends BaseController
{
    /**
     * Declare the rules for the form validation
     *
     * @var array
     */
    protected $validationRules1 = array(
            "purchase_date"              => "required|date",
            "car_name"                   => "required|max:40",
            "car_year"                   => "required|max:8",
            "chasis_no"                  => "required|max:40",
            "service_company_id"         => "required|integer",
            "car_auction_id"             => "required|integer",
            "exhibit_number"             => "integer",
            "customer_id"                => "required|integer",
    );
    protected $validationRules2 = array(
        'purchase_price'            => "integer",
        'vat_percent'               => "integer",
        'recycle_amount'            => "integer",
        'auction_commission'        => "integer",
        'car_tax_amount'            => "integer",
        'transfer_fee'              => "integer",
        'others'                    => "integer",
        'vanning'                   => "integer",
    );
    protected $validationRulesStep1 = array(
            "service_company_id"      => "required|integer",
            #"car_auction_type"        => "required",
            "car_auction_id"          => "required",
            #"customer_id"             => "required",
            "container_port"          => "max:40",
    );
    protected $validationRulesStep2 = array(
        # basic
        "purchase_date"              => "required|date",
        "car_maker"                  => "required|max:40",
        "car_name"                   => "required|max:40",
        "car_year"                   => "required|max:8",
        "car_year_month"             => "max:8",
        "chasis_no"                  => "required|max:40",
        "lot_no"                     => "integer",
        //'auction_sheet_upload'       => "application|mimes:pdf|max:30000000",
        # pay
        'payment_total_amount'      => "integer",
        'purchase_price'            => "integer",
        'vat_percent'               => "integer",
        'recycle_amount'            => "integer",
        'auction_commission'        => "integer",
        'car_tax_amount'            => "integer",
        'transfer_fee'              => "integer",
        'others'                    => "integer",
        'vanning'                   => "integer",
    );
    protected $validationRulesBill = array(
        # bill
        'bill_total_amount'     => "integer",
        'bill_price'            => "integer",
        'bill_vat'              => "integer",
        'bill_recycle'          => "integer",
        'bill_rakusatu'         => "integer",
        'bill_transport_fee'    => "integer",
        'bill_vanning'          => "integer",
        'bill_others'           => "integer",
        'bill_commission'       => "integer",
    );

    protected $validationRules = array(
        # basic
        "purchase_date"              => "required|date",
        "car_maker"                  => "required|max:40",
        "car_name"                   => "required|max:40",
        "car_year"                   => "required|max:8",
        "chasis_no"                  => "required|max:40",
        "lot_no"                     => "integer",
        //'auction_sheet_upload'       => "image|mimes:jpg,jpeg,gif,png|max:3000000",
        # pay
        'payment_total_amount'      => "integer",
        'purchase_price'            => "integer",
        'vat_percent'               => "integer",
        'recycle_amount'            => "integer",
        'auction_commission'        => "integer",
        'car_tax_amount'            => "integer",
        'others'                    => "integer",
        'vanning'                   => "integer",
        # bill
        'bill_total_amount'     => "integer",
        'bill_price'            => "integer",
        'bill_vat'              => "integer",
        'bill_recycle'          => "integer",
        'bill_rakusatu'         => "integer",
        'bill_transport_fee'    => "integer",
        'bill_vanning'          => "integer",
        'bill_others'           => "integer",
        'bill_commission'       => "integer",
    );

    protected $validationRulesPenalty = array(
        'penalty_date'          => "required|date",
        'penalty_type'          => "required|integer",
        'penalty_amount'        => "required|integer",
    );

    /**
     * PurchaseCar create step1.
     *
     * @return View
     */
    public function getCreateStep1()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Show the page
        return View::make('nimo.domains.car_balance.Main.car_create_step1')
            ->with('customer_list', array_merge(array(''),Customer::lists('name', 'id')))
            ->with('car_auction_type_list', CarAuctionType::lists('name', 'id'))
            ->with('car_auction_list', CarAuction::lists('name', 'id'))
            ->with('service_company_list', ServiceCompany::lists('name', 'id'))
            ->with('container_ports', array_merge(array(''),VanningCompanyBranch::lists('name', 'id')))
        ;
    }

    /**
     * PurchaseCar create step1 form processing.
     *
     * @return Redirect
     */
    public function postCreateStep1()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRulesStep1);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        // set data to session
        $step1_data = array(
            'customer_id' =>        Input::get('customer_id'),
            'car_auction_type' =>   Input::get('car_auction_type'),
            'car_auction_id' =>     Input::get('car_auction_id'),
            'service_company_id' => Input::get('service_company_id'),
            'container_port' =>     Input::get('container_port'),
        );
        Session::set('car_create_step1', $step1_data);

        // Redirect to the new purchase_car step2 page
        return Redirect::route("car_balance.car.create");
    }

    /**
     * PurchaseCar create.
     *
     * @return View
     */
    public function getCreate()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        $car_makers = array_merge(array(''),CarMaker::orderBy('node_left')->where('node_parent', '=', null)->lists('name2'));
        $step1_data = Session::get('car_create_step1');
        $transport_fee = $this->calcTransportFeePay($step1_data['car_auction_id'], $step1_data['container_port']);
        $customer_bill_type = new CustomerBillType();
        $commission_1 = $customer_bill_type::where('bill_type', '=', 1)->first()->commission;
        $commission_2 = $customer_bill_type::where('bill_type', '=', 2)->first()->commission;
        $commission_3 = $customer_bill_type::where('bill_type', '=', 3)->whereNull('date_to')->first()->commission;
        $bill_transport_fee_1 = $this->calcTransportFeeClaim($step1_data['car_auction_id'], $step1_data['container_port'], 1);
        $bill_transport_fee_2 = $this->calcTransportFeeClaim($step1_data['car_auction_id'], $step1_data['container_port'], 2);
        $bill_transport_fee_4 = $this->calcTransportFeeClaim($step1_data['car_auction_id'], $step1_data['container_port'], 4);
//        $bill_transport_fee->TransportFeeClaim();
//        $manual_bill = !in_array($step1_data['customer_id'], array('KG', 'BH', 'CH'));
        // Show the page
        return View::make('nimo.domains.car_balance.Main.car_create')
            ->with('customer_list', Customer::lists('name', 'id'))
            ->with('container_ports', VanningCompanyBranch::lists('name', 'id'))
            ->with('car_auction_list', CarAuction::lists('name', 'id'))
            ->with('car_auction_type_list', CarAuctionType::lists('name', 'id'))
            ->with('service_company_list', ServiceCompany::lists('name', 'id'))
            ->with('car_makers', array_combine($car_makers, $car_makers))
            ->with('step1_data', $step1_data)
            ->with('transport_fee', $transport_fee)
            ->with('commission_1', $commission_1)
            ->with('commission_2', $commission_2)
            ->with('commission_3', $commission_3)
            ->with('bill_transport_fee_1', $bill_transport_fee_1)
            ->with('bill_transport_fee_2', $bill_transport_fee_2)
            ->with('bill_transport_fee_4', $bill_transport_fee_4)
//            ->with('manual_bill', $manual_bill)
        ;
    }
    public function getCarNames()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        $maker = Request::get('maker');
        $model = Request::get('model');
        $filter = Request::get('filter');
        $maker = CarMaker::where('name2', '=', $maker)->where('node_parent', '=', null)->first();
        if ($filter) {
            if ($maker) {
                $car_names = array_merge(array(''),CarMaker::where('node_parent', '=', $maker->id)->orderBy('node_left','asc')->lists('name2', 'name2'));
            }
            else {
                $car_names = array();
            }
        }
        else {
            $car_names = CarMaker::where('node_parent', '=', $maker->id)->orderBy('node_left','asc')->lists('name2', 'name2');
        }
        return View::make('nimo.domains.car_balance.Main.car_names', compact('car_names'))
            ->with('model', $model);
    }

    /**
     * PurchaseCar create form processing.
     *
     * @return Redirect
     */
    public function postCreate()
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRulesStep2);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        $step1_data = Session::get('car_create_step1');

        // Create a new purchase_car
        $purchase_car = new PurchaseCar();

        // Update the purchase_car data
        foreach($this->validationRulesStep2 as $field => $rule)
            if(e(Input::get($field)))
                $purchase_car->{$field} = e(Input::get($field));

        $file = Input::file('auction_sheet_upload');
        if($file) {
            $destinationPath = Config::get('app.uploads.auction');
            $filename = 'auction_sheet_'.strtoupper($purchase_car->chasis_no).'.pdf'; // str_random(8).$file->getClientOriginalName();

            $upload_success = Input::file('auction_sheet_upload')->move($destinationPath, $filename);
            if( $upload_success ) {
                $purchase_car->auction_sheet_upload_flag = true;
            } else {
                $purchase_car->auction_sheet_upload_flag = false;
            }
        }
        //from session (step1)
        $purchase_car->service_company_id         = $step1_data['service_company_id'];
        $purchase_car->auction_type               = $step1_data['car_auction_type'];
        $purchase_car->auction_name               = $step1_data['car_auction_id'];
        $purchase_car->customer_id                = $step1_data['customer_id'];
        $purchase_car->container_port             = $step1_data['container_port'];
        if (e(Input::get('number_plate_flag')) == 'on') {
            $purchase_car->number_plate_flag = true;
        }
        else {
            $purchase_car->number_plate_flag = false;
        }

        // TIC send fee
        if($purchase_car->service_company_id == 1) {
            $purchase_car->tic_send_fee = 480;
        } else {
            $purchase_car->tic_send_fee = 0;
        }

        // calculations
        // payment total amount
        $vat_amount = ($purchase_car->purchase_price * $purchase_car->vat_percent) / 100;
        $purchase_car->transfer_fee_1 = $purchase_car->transfer_fee;
        $purchase_car->payment_total_amount =
              intval($purchase_car->purchase_price)
            + intval($vat_amount)
            + intval($purchase_car->recycle_amount)
            + intval($purchase_car->auction_commission)
            + intval($purchase_car->car_tax_amount)
            + intval($purchase_car->tic_send_fee)
            + intval($purchase_car->transfer_fee)
            + intval($purchase_car->others)
            + intval($purchase_car->vanning)
        ;
        // transport fee
//        $purchase_car->calcTransportFeePay();

        // BILL
        // BH set
        if( e(Input::get('active_tab_1')) == '1' ) {
            $purchase_car->bill_type = 1;
            $purchase_car->bill_price = e(Input::get('bill_price_1'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_1'));
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = null;
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_1'));
            $purchase_car->bill_vanning = null;
            $purchase_car->bill_others = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_1'));
        // CH set
        } elseif ( e(Input::get('active_tab_2')) == '1' ) {
            $purchase_car->bill_type = 2;
            $purchase_car->bill_price = e(Input::get('bill_price_2'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_2'));
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_2'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_2'));
            $purchase_car->bill_others = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_2'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_2'));
        // KG set
        } elseif ( e(Input::get('active_tab_3')) == '1' ) {
            $purchase_car->bill_type = 3;
            $purchase_car->bill_price = e(Input::get('bill_price_3'));
            $purchase_car->bill_vat = null;
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = null;
            $purchase_car->bill_transport_fee = null;
            $purchase_car->bill_others = null;
            $purchase_car->bill_vanning = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_3'));
        // NMC set
        } elseif( e(Input::get('active_tab_4')) == '1' ) {
            $purchase_car->bill_type = 4;
            $purchase_car->bill_price = e(Input::get('bill_price_4'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_4'));
            $purchase_car->bill_recycle = e(Input::get('bill_recycle_4'));
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_4'));
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_4'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_4'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_4'));
            $purchase_car->bill_others = e(Input::get('bill_others_4'));
            $purchase_car->bill_commission = e(Input::get('bill_commission_4'));
        // Other set
        } else {
            $purchase_car->bill_type = 0;
            $purchase_car->bill_price = e(Input::get('bill_price_0'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_0'));
            $purchase_car->bill_recycle = e(Input::get('bill_recycle_0'));
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_0'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_0'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_0'));
            $purchase_car->bill_others = e(Input::get('bill_others_0'));
            $purchase_car->bill_commission = e(Input::get('bill_commission_0'));
        }

        $purchase_car->bill_total_amount =
            intval($purchase_car->bill_price)
            + intval(($purchase_car->bill_price*$purchase_car->bill_vat)/100)
            + intval($purchase_car->bill_recycle)
            + intval($purchase_car->bill_rakusatu)
            + intval($purchase_car->bill_transport_fee)
            + intval($purchase_car->bill_vanning)
            + intval($purchase_car->bill_others)
            + intval($purchase_car->bill_commission)
        ;

        //$purchase_car->calcBill($step1_data['customer_id']);

        // Was the purchase_car created?
        if($purchase_car->save())
        {
            // Redirect to the new purchase_car page
            //return Redirect::route("car_balance/main/car/")->with('id', $purchase_car->id)->with('success', 'PurchaseCar created successfully');

            return Redirect::route('car_balance.car.car_show', array('id' => $purchase_car->id))->with('success', 'PurchaseCar created successfully');
        }

        // Redirect to the purchase_car create page
        return Redirect::route('car_balance.car.create')->with('error', 'PurchaseCar was not created, please try again.');
    }

    /**
     * PurchaseCar edit expense.
     *
     * @param  int  $id
     * @return View
     */
    public function getEditExpense($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }

        // Show the page
        return View::make('nimo.domains.car_balance.Main.car_expense', compact('purchase_car'))
            ->with('vanning_company_branch_list', VanningCompanyBranch::lists('name', 'id'))
        ;
    }

    /**
     * PurchaseCar edit expense form processing.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postEditExpense($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRules2);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        // Update the purchase_car data
        /*$purchase_car->purchase_price             = e(Input::get('purchase_price'));
        $purchase_car->purchase_price_fixed       = e(Input::get('purchase_price_fixed'));
        $purchase_car->consumption_tax            = e(Input::get('consumption_tax'));
        $purchase_car->recycle_fee                = e(Input::get('recycle_fee'));
        $purchase_car->car_certification          = e(Input::get('car_certification'));
        $purchase_car->auction_comission          = e(Input::get('auction_comission'));
        $purchase_car->transport_fee_japan        = e(Input::get('transport_fee_japan'));
        $purchase_car->transport_fee_japan_fxd    = e(Input::get('transport_fee_japan_fxd'));
        $purchase_car->nmh_commision              = e(Input::get('nmh_commision'));
        $purchase_car->vanning_company_branch_id  = e(Input::get('vanning_company_branch_id'));
        $purchase_car->comment                    = e(Input::get('comment'));
        $purchase_car->auction_penalty            = e(Input::get('auction_penalty'));*/
        $purchase_car->purchase_price             = e(Input::get('purchase_price'));
        $purchase_car->vat_percent                = e(Input::get('vat_percent'));
        $purchase_car->recycle_amount             = e(Input::get('recycle_amount'));
        $purchase_car->auction_commission         = e(Input::get('auction_commission'));
        $purchase_car->car_tax_amount             = e(Input::get('car_tax_amount'));
        $purchase_car->transfer_fee               = e(Input::get('transfer_fee'));
        $purchase_car->others                     = e(Input::get('others'));
        $purchase_car->vanning                    = e(Input::get('vanning'));

        // Was the purchase_car updated?
        if($purchase_car->save())
        {
            // Redirect to the PurchaseCar page
            return Redirect::route('car_balance.main.car_list')->with('success', 'PurchaseCar edited successfully');
        }

        // Redirect to the PurchaseCar expense management page
        return Redirect::route('car_balance.car.expense', array('id' => $purchase_car->id))->with('error', 'Error occurred, please try again.');
    }


    /**
     * PurchaseCar update.
     *
     * @param  int  $id
     * @return View
     */
    public function getEdit($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        $car_makers = array_merge(array(''),CarMaker::orderBy('node_left')->where('node_parent', '=', null)->lists('name2'));
        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "PurchaseCar [$id] does not exist.");
        }

        // Show the page
        return View::make('nimo.domains.car_balance.Main.car_edit', compact('purchase_car'))
            ->with('customer_list', Customer::lists('name', 'id'))
            ->with('car_auction_type_list', CarAuctionType::lists('name', 'id'))
            ->with('car_auction_list', CarAuction::lists('name', 'id'))
            ->with('service_company_list', ServiceCompany::lists('name', 'id'))
            ->with('container_ports', array_merge(array(''),VanningCompanyBranch::lists('name', 'id')))
            ->with('car_makers', array_combine($car_makers, $car_makers))
            ;
    }

    /**
     * PurchaseCar update form processing page.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postEdit($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "PurchaseCar [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRules);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        // Update the purchase_car data
        $purchase_car->customer_id        = e(Input::get('customer_id'));
        $purchase_car->auction_type       = e(Input::get('car_auction_type'));
        $purchase_car->auction_name       = e(Input::get('car_auction_id'));
        $purchase_car->service_company_id = e(Input::get('service_company_id'));
        $purchase_car->container_port     = e(Input::get('container_port'));
        $purchase_car->purchase_date      = e(Input::get('purchase_date'));
        $purchase_car->lot_no             = e(Input::get('lot_no'));
        $purchase_car->car_maker          = e(Input::get('car_maker'));
        $purchase_car->car_name           = e(Input::get('car_name'));
        $purchase_car->car_year           = e(Input::get('car_year'));
        $purchase_car->car_year_month     = e(Input::get('car_year_month'));
        $purchase_car->chasis_no          = e(Input::get('chasis_no'));
        if (e(Input::get('number_plate_flag')) == 'on') {
            $purchase_car->number_plate_flag = true;
        }
        else {
            $purchase_car->number_plate_flag = false;
        }
        $purchase_car->purchase_price     = e(Input::get('purchase_price'));
        $purchase_car->vat_percent        = e(Input::get('vat_percent'));
        $purchase_car->recycle_amount     = e(Input::get('recycle_amount'));
        $purchase_car->auction_commission = e(Input::get('auction_commission'));
        $purchase_car->car_tax_amount     = e(Input::get('car_tax_amount'));
        $purchase_car->transfer_fee_1     = e(Input::get('transfer_fee_1'));
        $purchase_car->transfer_fee_2     = e(Input::get('transfer_fee_2'));
        $purchase_car->transfer_fee       = $purchase_car->transfer_fee_1 + $purchase_car->transfer_fee_2;
        $purchase_car->drayage            = e(Input::get('drayage'));
        $purchase_car->customs            = e(Input::get('customs'));
        $purchase_car->bl_fee             = e(Input::get('bl_fee'));
        $purchase_car->others             = e(Input::get('others'));
        $purchase_car->vanning_1          = e(Input::get('vanning_1'));
        $purchase_car->vanning_2          = e(Input::get('vanning_2'));
        $purchase_car->vanning            = $purchase_car->vanning_1 + $purchase_car->vanning_2;

        // TIC send fee
        if($purchase_car->service_company_id == 1) {
            $purchase_car->tic_send_fee = 480;
        } else {
            $purchase_car->tic_send_fee = 0;
        }

        $vat_amount = ($purchase_car->purchase_price * $purchase_car->vat_percent) / 100;
        $purchase_car->payment_total_amount =
            intval($purchase_car->purchase_price)
            + intval($vat_amount)
            + intval($purchase_car->recycle_amount)
            + intval($purchase_car->auction_commission)
            + intval($purchase_car->car_tax_amount)
            + intval($purchase_car->tic_send_fee)
            + intval($purchase_car->transfer_fee)
            + intval($purchase_car->others)
            + intval($purchase_car->vanning)
            + intval($purchase_car->drayage)
            + intval($purchase_car->customs)
            + intval($purchase_car->bl_fee)
        ;

        // BILL
        // BH set
        if( e(Input::get('active_tab_1')) == '1' ) {
            $purchase_car->bill_type = 1;
            $purchase_car->bill_price = e(Input::get('bill_price_1'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_1'));
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = null;
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_1'));
            $purchase_car->bill_vanning = null;
            $purchase_car->bill_others = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_1'));
            // CH set
        } elseif ( e(Input::get('active_tab_2')) == '1' ) {
            $purchase_car->bill_type = 2;
            $purchase_car->bill_price = e(Input::get('bill_price_2'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_2'));
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_2'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_2'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_2'));
            $purchase_car->bill_others = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_2'));
            // KG set
        } elseif ( e(Input::get('active_tab_3')) == '1' ) {
            $purchase_car->bill_type = 3;
            $purchase_car->bill_price = e(Input::get('bill_price_3'));
            $purchase_car->bill_vat = null;
            $purchase_car->bill_recycle = null;
            $purchase_car->bill_rakusatu = null;
            $purchase_car->bill_transport_fee = null;
            $purchase_car->bill_vanning = null;
            $purchase_car->bill_others = null;
            $purchase_car->bill_commission = e(Input::get('bill_commission_3'));
            // NMC set
        } elseif( e(Input::get('active_tab_4')) == '1' ) {
            $purchase_car->bill_type = 4;
            $purchase_car->bill_price = e(Input::get('bill_price_4'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_4'));
            $purchase_car->bill_recycle = e(Input::get('bill_recycle_4'));
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_4'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_4'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_4'));
            $purchase_car->bill_others = e(Input::get('bill_others_4'));
            $purchase_car->bill_commission = e(Input::get('bill_commission_4'));
            // Other set
        } else {
            $purchase_car->bill_type = 0;
            $purchase_car->bill_price = e(Input::get('bill_price_0'));
            $purchase_car->bill_vat = e(Input::get('bill_vat_0'));
            $purchase_car->bill_recycle = e(Input::get('bill_recycle_0'));
            $purchase_car->bill_rakusatu = e(Input::get('bill_rakusatu_0'));
            $purchase_car->bill_transport_fee = e(Input::get('bill_transport_fee_0'));
            $purchase_car->bill_vanning = e(Input::get('bill_vanning_0'));
            $purchase_car->bill_others = e(Input::get('bill_others_0'));
            $purchase_car->bill_commission = e(Input::get('bill_commission_0'));
        }

        $purchase_car->bill_total_amount =
            intval($purchase_car->bill_price)
            + intval(($purchase_car->bill_price*$purchase_car->bill_vat)/100)
            + intval($purchase_car->bill_recycle)
            + intval($purchase_car->bill_rakusatu)
            + intval($purchase_car->bill_transport_fee)
            + intval($purchase_car->bill_vanning)
            + intval($purchase_car->bill_others)
            + intval($purchase_car->bill_commission)
        ;

        $purchase_car->container_id   = e(Input::get('container_id'));
        $purchase_car->container_no   = e(Input::get('container_no'));
        $purchase_car->container_date = e(Input::get('container_date'));

        $file = Input::file('auction_sheet_upload');
        if($file) {
            $destinationPath = Config::get('app.uploads.auction');
            $filename = 'auction_sheet_'.strtoupper($purchase_car->chasis_no).'.pdf'; // str_random(8).$file->getClientOriginalName();

            $upload_success = Input::file('auction_sheet_upload')->move($destinationPath, $filename);
            if( $upload_success ) {
                $purchase_car->auction_sheet_upload_flag = true;
            } else {
                $purchase_car->auction_sheet_upload_flag = false;
            }
        }

        // Was the purchase_car updated?
        if($purchase_car->save())
        {
            // Redirect to the PurchaseCar page
            return Redirect::route('car_balance.car.car_show', array('id' => $purchase_car->id))->with('success', 'PurchaseCar updated successfully.');
        }

        // Redirect to the PurchaseCar management page
        return Redirect::route('car_balance.car.car_edit', array('id' => $purchase_car->id))->with('error', 'PurchaseCar was not updated, please try again');
    }

    /**
     * Delete the given purchase_car.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function getDelete($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', 'There was an issue deleting the PurchaseCar. Please try again.');
        }


        // Delete the purchase_car
        $purchase_car->delete();
        //$purchase_car->deletet_at = new DateTime('NOW');

        // Redirect to the PurchaseCar list page
        return Redirect::route("car_balance.main.car_list")->with('success', 'PurchaseCar was successfully deleted.');
    }

    public function purchaseCar($id)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator', 'customer'));
        $prev = Session::get('prevCarId'.$id);
        $next = Session::get('nextCarId'.$id);
        // Check if the purchase_car exists
        if (is_null($car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "PurchaseCar [$id] does not exist.");
        }

        // only for customer
        $user = Sentry::getUser();
        if($user->hasAccess('customer', false)) {
            if(!$user->isOwnedCar($car)) {
                App::abort(403, 'Хандах эрх хүрэлцэхгүй байна!');
            }
            $customer = $user;
        }

        $penalties = Penalty::where('chasis_no', '=', $car->chasis_no)->get();
        $re_auctions = ReAuction::where('purchase_car_id', '=', $car->id)->get();

        return View::make('nimo.domains.car_balance.Main.purchase_car')
            ->with('car', $car)
            ->with('prev', $prev)
            ->with('next', $next)
            //->with('container', $container)
            ->with('penalties', $penalties)
            ->with('customer', $customer)
            ->with('re_auctions', $re_auctions);
    }

    public function calcTransportFeePay($auction_name, $container_port)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        $tfp = new TransportFeePay();
        $tfp = $tfp->where('car_auction_id', '=', $auction_name)->where('vanning_company_branch_id', '=', $container_port)->first();
        if ($tfp) {
            return intval($tfp->fee);
        } else {
            return 0;
        }
    }

    public function calcTransportFeeClaim($auction_name, $container_port, $bill_type)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        if (is_null($container_port)) {
            return 0;
        } else {
            $car = new PurchaseCar();
            $car = $car->where('car_auction_id', '=', $auction_name)->where('container_port', '=', $container_port)->where('customer_id', '=', $bill_type)->orderBy('purchase_date', 'DESC')->first();
            if ($car) {
                return intval($car->bill_transport_fee);
            } else {
                $btf = new TransportFeeClaim();
                $btf = $btf->where('car_auction_id', '=', $auction_name)->where('vanning_company_branch_id', '=', $container_port)->first();
                if ($btf) {
                    return intval($btf->fee);
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * PurchaseCar edit expense.
     *
     * @param  int  $id
     * @return View
     */
    public function getCreatePenalty($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }

        // Show the page
        return View::make('nimo.domains.car_balance.Main.create_penalty', compact('purchase_car'))
            ;
    }

    /**
     * PurchaseCar edit expense form processing.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postCreatePenalty($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRulesPenalty);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        $penalty = new Penalty();
        $penalty->customer_id    = $purchase_car->customer->id;
        $penalty->chasis_no      = $purchase_car->chasis_no;
        $penalty->penalty_date   = e(Input::get('penalty_date'));
        $penalty->penalty_type   = e(Input::get('penalty_type'));
        $penalty->penalty_amount = e(Input::get('penalty_amount'));

        // Was the purchase_car updated?
        if($penalty->save())
        {
            // Redirect to the PurchaseCar page
            return Redirect::route('car_balance.car.car_show', array('id' => $purchase_car->id))->with('success', 'Penalty created successfully');
        }

        // Redirect to the PurchaseCar expense management page
        return Redirect::route('car_balance.car.create_penalty')->with('error', 'Error occurred, please try again.');
    }

    /**
     * PurchaseCar edit expense.
     *
     * @param  int  $id
     * @return View
     */
    public function getEditPenalty($id = null, $penaltyId = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($penalty = Penalty::find($penaltyId)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.car.car_show', array('id' => $id))->with('error', "Penalty [$id] does not exist.");
        }

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }


        // Show the page
        return View::make('nimo.domains.car_balance.Main.edit_penalty', compact('penalty', 'purchase_car'))
            ;
    }

    /**
     * PurchaseCar edit expense form processing.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function postEditPenalty($id = null, $penaltyId = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($penalty = Penalty::find($penaltyId)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.car.car_show', array('id' => $id))->with('error', "Penalty [$id] does not exist.");
        }

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', "Car [$id] does not exist.");
        }

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $this->validationRulesPenalty);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            // Ooops.. something went wrong
            return Redirect::back()->withInput()->withErrors($validator);
        }

        $penalty->penalty_date   = e(Input::get('penalty_date'));
        $penalty->penalty_type   = e(Input::get('penalty_type'));
        $penalty->penalty_amount = e(Input::get('penalty_amount'));

        // Was the purchase_car updated?
        if($penalty->save())
        {
            // Redirect to the PurchaseCar page
            return Redirect::route('car_balance.car.car_show', array('id' => $purchase_car->id))->with('success', 'Penalty created successfully');
        }

        // Redirect to the PurchaseCar expense management page
        return Redirect::route('car_balance.car.edit_penalty', array('id' => $id, 'penaltyId' => $penaltyId))->with('error', 'Error occurred, please try again.');
    }

    /**
     * Delete the given purchase_car.
     *
     * @param  int  $id
     * @return Redirect
     */
    public function getDeletePenalty($id = null, $penaltyId = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));

        // Check if the purchase_car exists
        if (is_null($penalty = Penalty::find($penaltyId)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.car.car_show', array('id' => $id))->with('error', "Penalty [$id] does not exist.");
        }

        // Check if the purchase_car exists
        if (is_null($purchase_car = PurchaseCar::find($id)))
        {
            // Redirect to the PurchaseCar management page
            return Redirect::route('car_balance.main.car_list')->with('error', 'There was an issue deleting the PurchaseCar. Please try again.');
        }

        if (is_null($penalty->bill_id)) {
            // Delete the penalty
            $penalty->delete();
        }
        //$purchase_car->deletet_at = new DateTime('NOW');

        // Redirect to the PurchaseCar list page
        return Redirect::route("car_balance.car.car_show", array('id' => $id))->with('success', 'Penalty was successfully deleted.');
    }

    public function postUpdateComment($id = null)
    {
        // only admin & operator can access
        $this->checkPermission(array('admin', 'operator'));
        
        $success = false;
        // Check if the purchase_car exists
        $purchase_car = PurchaseCar::find($id);
        if (!is_null($purchase_car)) {
            $purchase_car->purchase_car_comment = Input::get('q');
            if($purchase_car->save()) {
               $success = true;
            }
        }
        if (Request::ajax()) {
            if ($success) {
                return Response::json(array('status' => 'fail', 'message' => 'Error occurred, please try again.'));
            }
            return Response::json(array('status' => 'success', 'message' => 'Comment updated.'));
        }
        return Redirect::route('car_balance.car.car_show', array('id' => $id));
    }

}
